package com.feng.dt.log;

import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Objects;
import java.util.Properties;

public class Log4j2ConnectionFactory {

    private final static Logger LOGGER = LoggerFactory.getLogger(Log4j2ConnectionFactory.class);

    private interface Singleton {
        Log4j2ConnectionFactory INSTANCE = new Log4j2ConnectionFactory();
    }

    private final DataSource dataSource;

    private Log4j2ConnectionFactory() {
        InputStream resource = this.getClass().getClassLoader().getResourceAsStream("db.properties");
        if (Objects.isNull(resource)) {
            LOGGER.error("加载db.properties文件失败");
            throw new RuntimeException("加载db.properties文件失败");
        };
        Properties properties = new Properties();
        try {
            properties.load(resource);
        } catch (IOException e) {
            LOGGER.error("加载db.properties文件失败");
        }

        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername(properties.getProperty("db.username"));
        dataSource.setPassword(properties.getProperty("db.password"));
        dataSource.setUrl(properties.getProperty("db.url"));
        dataSource.setDriverClassName(properties.getProperty("db.driverClass"));
//        this.dataSource = StringUtil.getApplicationContext().getBean(DataSource.class);
        this.dataSource = dataSource;
    }

    public static Connection getDatabaseConnection() throws SQLException {
        return Singleton.INSTANCE.dataSource.getConnection();
    }

}
